package v1alpha1

import (
	"fmt"
	"phant-operator/pkg/apis/label"
)

func (pg *PostgresCluster) GetInstanceName() string {
	labels := pg.ObjectMeta.GetLabels()
	// Keep backward compatibility for helm.
	// This introduce a hidden danger that change this label will trigger rolling-update of most of the components
	// TODO(aylei): disallow mutation of this label or adding this label with value other than the cluster name in ValidateUpdate()
	if inst, ok := labels[label.InstanceLabelKey]; ok {
		return inst
	}
	return pg.Name
}

func (mt MemberType) String() string {
	return string(mt)
}

// PatroniImage return the postgres image with Patroni inside.
//
// If PD isn't specified, return empty string.
func (pg *PostgresCluster) PatroniImage() string {
	if pg.Spec.Postgres == nil {
		return ""
	}

	image := pg.Spec.Postgres.Image
	baseImage := pg.Spec.Postgres.BaseImage
	// base image takes higher priority
	if baseImage != "" {
		version := pg.Spec.Postgres.Version
		if version == nil {
			version = &pg.Spec.Version
		}
		if *version == "" {
			image = baseImage
		} else {
			image = fmt.Sprintf("%s:%s", baseImage, *version)
		}
	}
	return image
}
